<?php
/* SVN FILE: $Id: uninstall.php 236 2009-10-02 00:09:40Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Uninstall Plugins
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 236 $
* @lastrevision $Date: 2009-10-02 00:09:40 +0000 (Fri, 02 Oct 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-10-02 00:09:40 +0000 (Fri, 02 Oct 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/modules_admin/plugin/uninstall.php $
*/


if ( ! defined( 'IN_ACP' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'admin.php'.";
	exit();
}

class admin_ibmarket_plugin_uninstall extends ipsCommand
{
	/**
	 * Skin object
	 *
	 * @access	private
	 * @var		object			Skin templates
	 */
	private $html;
	
	/**
	 * Main class entry point
	 *
	 * @access	public
	 * @param	object		ipsRegistry reference
	 * @return	void		[Outputs to screen]
	 */
	public function doExecute( ipsRegistry $registry )
	{
		$this->registry->getClass('class_permissions')->checkPermissionAutoMsg( 'manage_plugin' );
		
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'admin_market', 'admin_plugins' ) );
		
		if($this->request['plugin'] == '..' || $this->request['plugin'] == '.' || !file_exists(IPSLib::getAppDir('ibmarket')."/plugins/".$this->request['plugin']."/xml/information.xml"))
		{
			$this->registry->output->showError($this->lang->words['cannot_find_plugin']);
		}
		
		require_once( IPS_KERNEL_PATH . 'classXML.php' );
		$xml = new classXML( $this->settings['gb_char_set'] );
		
		$xml->load( IPSLib::getAppDir('ibmarket')."/plugins/".$this->request['plugin']."/xml/information.xml" );
		
		// How not use use the array
		if(!$data = $xml->fetchElements('data'))
		{
			$this->registry->output->showError($this->lang->words['cannot_find_plugin']);
		}
		$data = $data->item(0);
		
		$this->plugin = array(
								'directory' => $this->request['plugin'],
								'name' => $xml->fetchItem($xml->fetchElements('name',$data)->item(0)),
								'xml' => $xml->fetchXMLAsArray(),
							);
		
		/* Sequence of Events:
			# Confirm Page
			# Uninstall
		*/		
		switch( $this->request['do'] )
		{
			default:
			case 'confirm':
				$this->confirmPage();
			break;
			case 'uninstall':
				$this->uninstall();
			break;
		}
		
		$this->registry->getClass('output')->html_main .= $this->registry->getClass('output')->global_template->global_frame_wrapper();
		$this->registry->getClass('output')->sendOutput();
	}
	
	/**
	 * Confirm uninstalling the plugin
	 *
	 * @access	public
	 * @return	void
	 **/
	public function confirmPage()
	{
		$this->html = $this->registry->output->loadTemplate('cp_skin_plugins');
		
		$plugin = isset($this->caches['market_plugin'][$this->request['plugin']]) ? $this->caches['market_plugin'][$this->request['plugin']] : $this->plugin;
		
		$items = array();
		foreach($this->caches['market_items'] as $item)
		{
			$dependicies = marketRegistry::getItem($item)->getDependcies();
			if(in_array($this->request['plugin'], $dependicies['plugin']))
			{
				$items[] = $item;
			}
		}
		
		$this->registry->output->html .= $this->html->confirmUninstall( $plugin, $items );
	}
	/**
	 * Run uninstall plugin
	 *
	 * @access	public
	 * @return	void
	 **/
	public function uninstall()
	{
		/* INIT */
		$output		= array();
		$errors		= array();
		$skipped	= 0;
		$count		= 0;
		
		//-----------------------------------------
		// Remove Items dependent on Plugin
		//-----------------------------------------
		foreach($this->caches['market_items'] as $item)
		{
			$dependicies = marketRegistry::getItem($item)->getDependcies();
			if(in_array($this->request['plugin'], $dependicies['plugin']))
			{
				$this->DB->delete('market_inventory',"item=".$item['item_id']);
				$this->DB->delete('market_items',"item_id=".$item['item_id']);
			}
		}
		
		//-----------------------------------------
		// Remove Plugin Caches
		//-----------------------------------------		
		
		$_file = IPSLib::getAppDir('ibmarket')."/plugins/".$this->request['plugin']."/caches.php";
		
		if ( file_exists( $_file ) )
		{
			require( $_file );
			
			if ( is_array( $CACHE ) AND count( $CACHE ) )
			{
				foreach( $CACHE as $key => $data )
				{
					$this->DB->delete( 'cache_store', "cs_key='{$key}'" );
				}
			}
		}
		
		//-----------------------------------------
		// Remove tables
		//-----------------------------------------
		
		$_file = IPSLib::getAppDir('ibmarket')."/plugins/".$this->request['plugin']."/install/" . strtolower( ipsRegistry::dbFunctions()->getDriverType() ) . "_tables.php";
		
		if( file_exists( $_file ) )
		{
			require( $_file );
			
			foreach( $TABLE as $q )
			{
				//-----------------------------------------
				// Capture create tables first
				//-----------------------------------------
				
				preg_match( "/CREATE TABLE (\S+)(\s)?\(/", $q, $match );
				
				if( $match[1] )
				{
					$this->DB->dropTable( preg_replace( '#^' . ipsRegistry::dbFunctions()->getPrefix() . "(\S+)#", "\\1", $match[1] ) );
				}
				else
				{
					//-----------------------------------------
					// Then capture alter tables
					//-----------------------------------------
					
					preg_match( "/ALTER TABLE (\S+)\sADD\s(\S+)\s/i", $q, $match );
					
					if( $match[1] AND $match[2] )
					{
						$this->DB->dropField( preg_replace( '#^' . ipsRegistry::dbFunctions()->getPrefix() . "(\S+)#", "\\1", $match[1] ), $match[2] );
					}
				}
			}
		}
		
		// TASKS
		/* XML Class */
		require_once( IPS_KERNEL_PATH.'class_xml.php' );
		$xml = new class_xml();		
		
		/* Read the xml file */
		$skin_content = implode( '', file( $file ) );
		
		/* Parse the xml file contents */
		$xml->xml_parse_document( $skin_content );
		
		/* Fix up */
		if ( ! is_array( $xml->xml_array['export']['group']['row'][0]  ) )
		{
			/* Ensure [0] is populated */
			$tmp = $xml->xml_array['export']['group']['row'];
			unset($xml->xml_array['export']['group']['row']);
			$xml->xml_array['export']['group']['row'][0] = $tmp;
		}
		
		/* Loop through the tasks */
		if ( is_array( $xml->xml_array['export']['group']['row'] ) AND count( $xml->xml_array['export']['group']['row'] ) )
		{
			foreach( $xml->xml_array['export']['group']['row'] as $id => $entry )
			{
				$newrow = array();
				
				$_key = $entry['task_key']['VALUE'];
				
				$this->DB->delete( 'task_manager', $newrow, "task_key='" . $_key . "'" );
			}
		}
		
		if($this->plugin['xml']['information']['data']['templategroups'])
		{
			$templateGroups = array();
			
			if(!isset($this->plugin['xml']['information']['data']['templategroups']['template'][0]))
			{
				$this->plugin['xml']['information']['data']['templategroups']['template'] = array(0 => $this->plugin['xml']['information']['data']['templategroups']['template']);
			}
			
			foreach($this->plugin['xml']['information']['data']['templategroups']['template'] as $template)
			{
				if($template['#alltext'])
				{
					$templateGroups[$template['#alltext']] = $template['@attributes']['match'];
				}
			}
			
			if( is_array($templateGroups) AND count($templateGroups) )
			{
				/* Loop through skin directories */
				try
				{
					foreach( new DirectoryIterator( DOC_IPS_ROOT_PATH . 'cache/skin_cache/' ) as $dir )
					{
						if( preg_match( "/^(cacheid_)/", $dir->getFileName() ) )
						{
							foreach( new DirectoryIterator( DOC_IPS_ROOT_PATH . 'cache/skin_cache/' . $dir->getFileName() . '/' ) as $file )
							{
								if( ! $file->isDot() )
								{
									foreach( $templateGroups as $name => $match )
									{
										if( $match == 'contains' )
										{
											if( stristr( $file->getFileName(), $name ) )
											{
												unlink( $file->getPathName() );
											}
										}
										else if( $file->getFileName() == $name . '.php' )
										{
											unlink( $file->getPathName() );
										}
									}
								}
							}
						}
					}
				} catch ( Exception $e ) {}
				
				/* Delete from database */
				foreach( $templateGroups as $name => $match )
				{
					if( $match == 'contains' )
					{
						$this->DB->delete( 'skin_templates', "template_group LIKE '%{$name}%'" );
					}
					else 
					{
						$this->DB->delete( 'skin_templates', "template_group='{$name}'" );
					}
				}
			}
		}
		
		if($this->plugin['xml']['information']['data']['languagepack'])
		{
			$languageFiles = array();
			
			if(!isset($this->plugin['xml']['information']['data']['languagepack']['pack'][0]))
			{
				$this->plugin['xml']['information']['data']['languagepack']['pack'] = array(0 => $this->plugin['xml']['information']['data']['languagepack']['pack']);
			}
			
			foreach($this->plugin['xml']['information']['data']['languagepack']['pack'] as $languageFile)
			{
				if($languageFile['#alltext'])
				{
					$languageFiles[] = $this->plugin['xml']['information']['data']['languagepack']['@attributes']['prefix']."_".$languageFile['#alltext'].".php";
				}
			}
			
			try
			{
				foreach( new DirectoryIterator( DOC_IPS_ROOT_PATH . 'cache/lang_cache/' ) as $dir )
				{
					if( ! $dir->isDot() && intval( $dir->getFileName() ) )
					{
						foreach( new DirectoryIterator( DOC_IPS_ROOT_PATH . 'cache/lang_cache/' . $dir->getFileName() . '/' ) as $file )
						{
							if( ! $file->isDot() )
							{
								if( in_array( $file->getFileName(), $languageFiles ) )
								{
									unlink( $file->getPathName() );
								}
							}
						}
					}
				}
			} catch ( Exception $e ) {}
		}
		
		// Remove from plugin
		$this->DB->delete('market_plugins',"directory='".$this->request['plugin']."'");
		
		/* Show redirect... */
		$this->registry->output->redirect( $this->settings['base_url']."module=plugin&amp;section=uninstall&amp;plugin=".$this->request['plugin']."&amp;do=languages", $messages, 2, true );
	}
	
}